import React, { useState, useEffect } from 'react';
import { Input, Button, message, Form, Typography } from 'antd';
import { useRouter } from 'next/router';
import styles from '../../pages/login/index.module.css';
import Image from 'next/image';

const { Title, Paragraph } = Typography;

// 模拟发送验证码的API调用
const sendVerificationCodeAPI = async (phone: string): Promise<boolean> => {
  // 这里是模拟API调用，实际开发中应该调用真实API
  return new Promise((resolve) => {
    setTimeout(() => {
      // 检查手机号格式是否正确
      if (/^1[3-9]\d{9}$/.test(phone)) {
        resolve(true);
      } else {
        resolve(false);
      }
    }, 500);
  });
};

// 模拟登录API调用
const loginAPI = async (phone: string, code: string): Promise<boolean> => {
  // 这里是模拟API调用，实际开发中应该调用真实API
  return new Promise((resolve) => {
    setTimeout(() => {
      // 这里简单模拟验证，实际应由服务端验证
      if (phone && code && code.length === 6) {
        resolve(true);
      } else {
        resolve(false);
      }
    }, 800);
  });
};

const LoginPageClient: React.FC = () => {
  const [form] = Form.useForm();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [sendingCode, setSendingCode] = useState(false);

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setTimeout(() => setCountdown(countdown - 1), 1000);
    }
    return () => {
      if (timer) clearTimeout(timer);
    };
  }, [countdown]);

  const handleSendVerificationCode = async () => {
    try {
      // 验证手机号
      await form.validateFields(['phone']);
      const phone = form.getFieldValue('phone');
      
      setSendingCode(true);
      const success = await sendVerificationCodeAPI(phone);
      
      if (success) {
        setCountdown(60); // 设置60秒倒计时
        message.success('验证码已发送');
      } else {
        message.error('验证码发送失败，请检查手机号是否正确');
      }
    } catch (error) {
      // 表单验证失败
    } finally {
      setSendingCode(false);
    }
  };

  const handleLogin = async (values: { phone: string; verificationCode: string }) => {
    setLoading(true);
    try {
      const success = await loginAPI(values.phone, values.verificationCode);
      if (success) {
        message.success('登录成功');
        // 登录成功后跳转到支付页
        router.push('/pay');
      } else {
        message.error('登录失败，请检查手机号和验证码');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      <div className={styles.header}>
        <div className={styles.logoContainer}>
          <Image 
            src="/pay/avatar1.png" 
            alt="Logo" 
            width={60} 
            height={60}
            className={styles.logo}
          />
        </div>
        <Title level={2} className={styles.title}>欢迎登录</Title>
        <Paragraph className={styles.subtitle}>
          请使用您的手机号和验证码登录系统
        </Paragraph>
      </div>

      <div className={styles.formContainer}>
        <Form
          form={form}
          name="loginForm"
          onFinish={handleLogin}
          layout="vertical"
          requiredMark={false}
        >
          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
            ]}
          >
            <Input
              size="large"
              placeholder="请输入手机号"
              className={styles.input}
              maxLength={11}
            />
          </Form.Item>

          <Form.Item
            name="verificationCode"
            label="验证码"
            rules={[
              { required: true, message: '请输入验证码' },
              { len: 6, message: '验证码为6位数字' }
            ]}
          >
            <div className={styles.verificationCodeContainer}>
              <Input
                size="large"
                placeholder="请输入验证码"
                className={styles.codeInput}
                maxLength={6}
              />
              <Button
                className={styles.codeButton}
                onClick={handleSendVerificationCode}
                disabled={countdown > 0}
                loading={sendingCode}
              >
                {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className={styles.loginButton}
              loading={loading}
              block
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>

      <div className={styles.footer}>
        <p>登录即表示同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a></p>
      </div>
    </div>
  );
};

export default LoginPageClient;
